package com.oktest.measure.ui.fragment.login

import android.os.Bundle
import cc.shinichi.library.tool.text.MD5Util
import com.cali.common.kt.checkedInputType
import com.cali.common.kt.jsonBody
import com.cali.common.kt.value
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.http.RetrofitManagement
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.http.Api
import com.oktest.measure.kt.API_SUCCESS_CODE
import com.oktest.measure.kt.resultTryContext
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.android.synthetic.main.fragment_reset_pwd.*
import kotlinx.coroutines.launch

/**
 * @Author hhh
 * @Date 2020/11/19
 */
class ResetFragment:BaseFragment() {
    override fun getLayoutId() = R.layout.fragment_reset_pwd

    override fun initData(savedInstanceState: Bundle?) {
        initTitle()
        tvReset.setOnClickListener {
            reset()
        }
        boxEnsureVisible.setOnCheckedChangeListener { buttonView, isChecked ->
            etPwdEnsure.checkedInputType(isChecked)
        }
        boxNewVisible.setOnCheckedChangeListener { buttonView, isChecked ->
            etPwdNew.checkedInputType(isChecked)
        }
    }

    private fun reset() = launch{
        val newPwd = etPwdNew.value()
        val ensurePwd = etPwdEnsure.value()
        if (newPwd.isEmpty()) {
            toast("密码不能为空")
            return@launch
        }
        if (ensurePwd.isEmpty()) {
            toast("确认密码不能为空")
            return@launch
        }
        if (newPwd != ensurePwd) {
            toast("密码和确认密码不相同")
            return@launch
        }
        val map = hashMapOf("memberId" to MyApp.memberId, "newPwd" to MD5Util.md5Encode(ensurePwd).toLowerCase())
        val body = map.jsonBody()
        val resetResult = resultTryContext {
            RetrofitManagement.instance.getService(Api::class.java)
                .resetPwd(body).execute().body()
        }
        if (resetResult.code == API_SUCCESS_CODE) {
            pop()
        } else {
            error(resetResult)
        }
    }

    private fun initTitle() {
        toolbarHelper?.apply {
            setTitleText("修改密码")
        }
    }

    override fun hasToolbar(): Boolean {
        return true
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }
}